package com.example.znyt.aop;

import com.example.znyt.annotation.AuthCheck;
import com.example.znyt.exception.BussinessException;
import com.example.znyt.exception.ErrorCode;
import com.example.znyt.model.entity.User;
import com.example.znyt.model.enums.UserRoleEnum;
import com.example.znyt.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Description 切面类定义用户权限
 * @Date 2025/6/15 10:23
 * @Created by 12336
 */

@Aspect
@Component
public class AuthInterceptor {
    @Resource
    private UserService userService;

    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint,  AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        //获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        UserRoleEnum  mustUserRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        //不需要权限，放行
        if(mustUserRoleEnum == null){
            return joinPoint.proceed();
        }
        //必须有权限，以下代码才会通过
        UserRoleEnum loginUserRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        if(loginUserRoleEnum == null){
            throw new BussinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //必须有管理员权限，但用户没有管理员权限,拒绝
        if(UserRoleEnum.ADMIN.equals(mustUserRoleEnum) && !UserRoleEnum.ADMIN.equals(loginUserRoleEnum)){
            throw new BussinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //放行
        return joinPoint.proceed();

    }


}
